<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-tabs type="border-card">
        <el-tab-pane label="基础信息">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称" maxlength="35"/>
          </el-form-item>
          <el-form-item label="缩略图" prop="thumbnail">
            <div class="upload">
              <div class="upload_warp">
                <div class="upload_warp_left" @click="thumbnailFileClick">
                  <img src="../../upload.png">
                </div>
                <div class="upload_warp_right" @drop="drop($event)" @dragenter="dragenter($event)"
                     @dragover="dragover($event)">
                  或者将文件拖到此处
                </div>
              </div>
              <input @change="thumbnailFileChange($event)" type="file" id="upload_goods_thum" multiple
                     style="display: none"/>
              <div class="upload_warp_img" v-show="thumbnailList.length!=0">
                <div class="upload_warp_img_div" v-for="(item,index) in thumbnailList"
                     :key="index"
                >
                  <div class="upload_warp_img_div_top">
                    <img src="../../del.png" class="upload_warp_img_div_del" @click="thumbnailFileDel(index)">
                  </div>
                  <img :src="item">
                </div>
              </div>
            </div>

          </el-form-item>
          <el-form-item label="商品图片" prop="banners">
            <div class="upload">
              <div class="upload_warp">
                <div class="upload_warp_left" @click="goodFileClick">
                  <img src="../../upload.png">
                </div>
                <div class="upload_warp_right" @drop="drop($event)" @dragenter="dragenter($event)"
                     @dragover="dragover($event)">
                  或者将文件拖到此处
                </div>
              </div>
              <input @change="goodFileChange($event)" type="file" id="upload_goods" multiple style="display: none"/>
              <div class="upload_warp_img" v-show="imgList.length!=0">
                <div class="upload_warp_img_div" v-for="(item,index) in imgList"
                     v-dragging="{ item: item, list: imgList, group: 'color' }"
                     :key="index">
                  <div class="upload_warp_img_div_top">
                    <img src="../../del.png" class="upload_warp_img_div_del" @click="goodFileDel(index)">
                  </div>
                  <img :src="item">
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="商品价格" prop="price">
            <el-input v-model="form.price" placeholder="请输入商品价格" @keyup="priceFormat" maxlength="12"
                      @keyup.native="form.price = form.price = form.price.replace(/[^\d.]/g,'');
                                     form.price = form.price.replace(/\.{2,}/g,'.');
                                     form.price = form.price.replace(/^\./g,'');
                                     form.price = form.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                                     form.price = form.price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
            />
          </el-form-item>
          <el-form-item label="成本价格" prop="cost">
            <el-input v-model="form.cost" placeholder="请输入成本价格" @keyup="priceFormat" maxlength="9"
                      @keyup.native="form.cost = form.cost = form.cost.replace(/[^\d.]/g,'');
                                     form.cost = form.cost.replace(/\.{2,}/g,'.');
                                     form.cost = form.cost.replace(/^\./g,'');
                                     form.cost = form.cost.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                                     form.cost = form.cost.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
            />
          </el-form-item>
          <el-form-item label="单位" prop="company">
            <el-select v-model="measurement"  filterable placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品排序" prop="sort">
            <el-input v-model="form.sort" maxlength="8" @input="v => form.sort = v.replace(/[^\d]/g,'')"
                      placeholder="请输入商品排序(默认为1)"/>
          </el-form-item>
          <el-form-item label="重量(克)" prop="weight">
            <el-input v-model="form.weight" placeholder="请输入重量(克)" @keyup="priceFormat"
                      maxlength="10"
                      @keyup.native="form.weight = form.weight = form.weight.replace(/[^\d.]/g,'');
                                     form.weight = form.weight.replace(/\.{2,}/g,'.');
                                     form.weight = form.weight.replace(/^\./g,'');
                                     form.weight = form.weight.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                                     form.weight = form.weight.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
            />
          </el-form-item>
          <el-form-item label="商品描述" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入商品描述" maxlength="50"/>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="关联属性">
          <el-form-item label="品牌" prop="brandId">
            <el-select
              v-model="form.brandId"
              placeholder="品牌"
              clearable
              size="small"
              style="width: 100%"
            >
              <el-option
                v-for="dict in brandList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
            <treeselect v-model="form.categoryId" :options="categoryOptions" :normalizer="normalizer"
                        style="width: 100%;" placeholder="选择分类"/>
          </el-form-item>
          <el-form-item label="标签" prop="labelsIds">
            <el-select v-model="labelsIds" multiple filterable placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="item in labelOptions"
                :key="item.id"
                :label="item.name"
                :value="item.labelKey"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库存阈值" prop="inventoryThreshold">
            <el-input v-model="form.inventoryThreshold" placeholder="请输入库存阈值" maxlength="11"
                      @input="v => form.inventoryThreshold = v.replace(/[^\d]/g,'')"/>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer" style="float: right; margin-bottom: 50px; margin-top: 20px;">
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </div>

</template>

<script>
import {get_minio_bucketName, get_minio_url, minioClient, random_string} from "../../../../minio";
import {listBrand} from "@/api/erp/brand"
import {listCategory} from "@/api/erp/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listLabel} from "@/api/erp/label";
import {addGoods} from "@/api/erp/goods";
import {listCompany, listCompanys} from "@/api/erp/company";

let stream = require('stream')

export default {
  name: "Goods",
  components: {Treeselect},
  data() {
    return {
      //计量单位
      measurement:null,
      //图片list
      imgList: [],
      //品牌list
      brandList: [],
      //缩略图list
      thumbnailList: [],
      //分类list
      categoryOptions: [],
      //标签集合
      labelOptions: [],
      //单位集合
      companyList: [],
      //标签集合
      labelsIds: [],
      //表单参数
      form: {},
      //表单校验
      rules: {
        price: [{required: true, message: '请输入价格', trigger: 'blur'},
          {
            pattern: /(^[1-9][0-9]{0,7}$)|(^((0\.0[1-9]$)|(^0\.[1-9]\d?)$)|(^[1-9][0-9]{0,7}\.\d{1,2})$)/,
            message: '价格错误',
            trigger: 'blur'
          }],

        name: [{required: true, message: '请输入名称', trigger: 'blur'}],

        categoryId: [{required: true, message: '请选择商品分类', trigger: 'blur'}],

        brandId: [{required: true, message: '请选择品牌', trigger: 'blur'}],
      }
    };
  },
  created() {
    this.getBrandList();
    this.getCategoryList();
    this.getLabelList();
    this.getCompanyList();
  },

  methods: {

    //获取标签列表
    getLabelList() {
      let params = {};
      listLabel(params).then(response => {
        this.labelOptions = response.rows;
      });
    },
    //获取单位列表
    getCompanyList(){
      let params = {};
      listCompanys(params).then(response =>{
        this.companyList = response.rows;
      })
    },

    //获取分类列表
    getCategoryList() {
      let params = {};
      listCategory(params).then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },

    //获取品牌列表
    getBrandList() {
      let params = {};
      listBrand(params).then(response => {
        this.brandList = response.rows;
      });
    },

    /*node分类节点*/
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },

    //新增商品提交按钮
    submitForm() {
      this.form.banners = JSON.stringify(this.imgList);
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.labels = JSON.stringify(this.labelsIds);
          this.form.company = this.measurement;
          addGoods(this.form).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.close();
            }
          });
        }
      });
    },

    //返回上一页商品列表页
    close() {
      this.$router.push({path: '/goodsList'});
    },

    //上传缩略图
    thumbnailFileClick() {
      document.getElementById('upload_goods_thum').click()
    },

    /*上传缩略图*/
    thumbnailFileChange(el) {
      if (this.thumbnailList.length > 0) {
        this.$modal.msgSuccess("请上传一张缩略图!");
        return;
      }
      this.uploadTPic(el.target.files[0])
    },

    //缩略图上传minio
    uploadTPic(fileObj, index) {
      let vm = this
      // const files = fileObj;
      if (fileObj) {
        let file = fileObj
        let that = this
        //判断是否选择了文件
        if (file == undefined) {
          //未选择
          console.log("请上传文件")
        } else {
          //选择
          //获取文件类型及大小
          const fileName = "goods/thumbnail/" + random_string(6) + '_' + new Date().getTime() + '.' + file.name.split('.').pop();
          const mineType = file.type
          const fileSize = file.size
          //参数
          let metadata = {
            "content-type": mineType,
            "content-length": fileSize
          }
          //判断储存桶是否存在
          minioClient.bucketExists(get_minio_bucketName(), function (err) {
            if (err) {
              if (err.code == 'NoSuchBucket') return console.log("bucket does not exist.")
              return console.log(err)
            }
            //存在
            console.log('Bucket exists.')
            //准备上传
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function (e) {
              const dataurl = e.target.result
              //base64转blob
              const blob = vm.toBlob(dataurl)
              //blob转arrayBuffer
              let reader2 = new FileReader()
              reader2.readAsArrayBuffer(blob)

              reader2.onload = function (ex) {
                //定义流
                let bufferStream = new stream.PassThrough();
                //将buffer写入
                bufferStream.end(new Buffer(ex.target.result));
                //上传
                minioClient.putObject(get_minio_bucketName(), fileName, bufferStream, fileSize, metadata, function (err, etag) {
                  if (err == null) {
                    minioClient.presignedGetObject(get_minio_bucketName(), fileName, 24 * 60 * 60, function (err, presignedUrl) {
                      if (err) return console.log(err)
                      //输出url
                      console.log(presignedUrl)
                      that.thumbnailList.push(get_minio_url() + fileName);
                      console.log(get_minio_url() + fileName + "------")
                      that.form.thumbnail = get_minio_url() + fileName;
                    })
                  }
                })
              }
            }
          })
        }
      }
    },

    //缩略图删除选项
    thumbnailFileDel(index) {
      this.thumbnailList.splice(index, 1);
    },

    //上传商品图片按钮
    goodFileClick() {
      document.getElementById('upload_goods').click()
    },

    /*上传商品图片到minio*/
    goodFileChange(el) {
      if (!el.target.files[0].size) return;
      this.fileList(el.target);
      el.target.value = '';
    },

    fileList(fileList) {
      let files = fileList.files;
      for (let i = 0; i < files.length; i++) {
        if (files[i].type != '') {
          this.fileAdd(files[i]);
        } else {
          this.folders(fileList.items[i]);
        }
      }
    },

    fileAdd(file) {
      if (this.limit === 0) return;
      this.limit--;
      //判断是否为图片文件
      if (file.type.indexOf('image') == -1) {
        file.src = 'wenjian.png';
      } else {
        let reader = new FileReader();
        let _this = this;
        reader.readAsDataURL(file);
        //上传minio
        _this.uploadPic(file);
      }
    },

    //文件夹处理
    folders(files) {
      let _this = this;
      //判断是否为原生file
      if (files.kind) {
        files = files.webkitGetAsEntry();
      }
      files.createReader().readEntries(function (file) {
        for (let i = 0; i < file.length; i++) {
          if (file[i].isFile) {
            _this.foldersAdd(file[i]);
          } else {
            _this.folders(file[i]);
          }
        }
      })
    },

    foldersAdd(entry) {
      let _this = this;
      entry.file(function (file) {
        _this.fileAdd(file)
      })
    },

    /*商品图片上传minio*/
    uploadPic(fileObj, index) {
      let vm = this
      // const files = fileObj;
      if (fileObj) {
        let file = fileObj
        let that = this
        //判断是否选择了文件
        if (file == undefined) {
          //未选择
          console.log("请上传文件")
        } else {
          //选择
          //获取文件类型及大小
          const fileName = "goods/banners/" + random_string(6) + '_' + new Date().getTime() + '.' + file.name.split('.').pop();
          const mineType = file.type
          const fileSize = file.size
          //参数
          let metadata = {
            "content-type": mineType,
            "content-length": fileSize
          }
          //判断储存桶是否存在
          minioClient.bucketExists(get_minio_bucketName(), function (err) {
            if (err) {
              if (err.code == 'NoSuchBucket') return console.log("bucket does not exist.")
              return console.log(err)
            }
            //存在
            console.log('Bucket exists.')
            //准备上传
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function (e) {
              const dataurl = e.target.result
              //base64转blob
              const blob = vm.toBlob(dataurl)
              //blob转arrayBuffer
              let reader2 = new FileReader()
              reader2.readAsArrayBuffer(blob)

              reader2.onload = function (ex) {
                //定义流
                let bufferStream = new stream.PassThrough();
                //将buffer写入
                bufferStream.end(new Buffer(ex.target.result));
                //上传
                minioClient.putObject(get_minio_bucketName(), fileName, bufferStream, fileSize, metadata, function (err, etag) {
                  if (err == null) {
                    minioClient.presignedGetObject(get_minio_bucketName(), fileName, 24 * 60 * 60, function (err, presignedUrl) {
                      if (err) return console.log(err)
                      //输出url
                      console.log(presignedUrl)
                      that.imgList.push(get_minio_url() + fileName);
                    })
                  }
                })
              }
            }
          })
        }
      }
    },

    //商品图片删除
    goodFileDel(index) {
      this.imgList.splice(index, 1);
      this.limit++; // = this.imgList.length;
      form.address = '';
    },

    //拖拽文件触发
    drop(el) {
      el.stopPropagation();
      el.preventDefault();
      this.fileList(el.dataTransfer);
    },

    //拖拽效果
    dragenter(el) {
      el.stopPropagation();
      el.preventDefault();
    },

    //拖拽效果
    dragover(el) {
      el.stopPropagation();
      el.preventDefault();
    },

    //base64转blob
    toBlob(base64Data) {
      let byteString = base64Data
      if (base64Data.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(base64Data.split(',')[1]) // base64 解码
      } else {
        byteString = unescape(base64Data.split(',')[1])
      }
      // 获取文件类型
      let mimeString = base64Data.split(';')[0].split(":")[1] // mime类型
      let uintArr = new Uint8Array(byteString.length) // 创建视图
      for (let i = 0; i < byteString.length; i++) {
        uintArr[i] = byteString.charCodeAt(i)
      }
      // 生成blob
      const blob = new Blob([uintArr], {
        type: mimeString
      })
      // 使用 Blob 创建一个指向类型化数组的URL, URL.createObjectURL是new Blob文件的方法,可以生成一个普通的url,可以直接使用,比如用在img.src上
      return blob
    },

    //价格重量表单校验
    priceFormat() {
      //非数字和小数点去掉
      this.form.price = this.price.replace(/[^0123456789.]/, "")
      //防止无输入无限个“.”
      this.form.price = this.price.replace(/\.+/, ".")
      //在不是“0.”开头的字符进行修改：“01”=>1
      if (this.form.price.charAt(0) == "0" && this.form.price.charAt(1) != "." && this.form.price.length >= 2) {
        this.form.price = this.form.price.replace(/0/, "")
      }
      //获取第一个小数点的索引值
      var index = this.form.price.indexOf('.')
      //获取最后一个小数点的索引值
      var lastIndex = this.form.price.lastIndexOf('.')
      //判断小数点是不是开头，如果是开头，则去除
      if (index == 0) {
        this.form.price = this.form.price.replace(/\./, "")
      }
      //只允许小数点后面有2位字符
      if (index >= 1) {
        this.form.price = this.form.price.substring(0, index + 3)
      }
      //防止小数点后面又出现小数点
      if (index != lastIndex) {
        this.form.price = this.form.price.substring(0, index + 2)
      }
    }
  }
}

</script>


<style scoped>
.upload_warp_img_div_del {
  position: absolute;
  top: 6px;
  width: 16px;
  right: 4px;
}

.upload_warp_img_div_top {
  position: absolute;
  top: 0;
  width: 25px;
  left: 295px;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.4);
  line-height: 30px;
  text-align: left;
  color: #fff;
  font-size: 12px;
  text-indent: 4px;
}


.upload_warp_img_div img {
  max-width: 100%;
  max-height: 100%;
  vertical-align: middle;
}

.upload_warp_img_div {
  position: relative;
  height: 200px;
  width: 320px;
  border: 1px solid #ccc;
  margin: 0px 30px 10px 0px;
  float: left;
  line-height: 100px;
  display: table-cell;
  text-align: center;
  background-color: #eee;
  cursor: pointer;
}

.upload_warp_img {
  border-top: 1px solid #D2D2D2;
  padding: 14px 0 0 14px;
  overflow: hidden
}


.upload_warp_right {
  float: left;
  width: 57%;
  margin-left: 2%;
  height: 100%;
  border: 1px dashed #999;
  border-radius: 4px;
  line-height: 130px;
  color: #999;
}

.upload_warp_left img {
  margin-top: 32px;
}

.upload_warp_left {
  float: left;
  width: 40%;
  height: 100%;
  border: 1px dashed #999;
  border-radius: 4px;
  cursor: pointer;
}

.upload_warp {
  margin: 14px;
  height: 130px;
}

.upload {
  border: 1px solid #ccc;
  background-color: #fff;
  width: 60%;
  box-shadow: 0px 1px 0px #ccc;
  border-radius: 4px;
  text-align: center;
}


</style>
